<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Tests — Web Components</title>
    <link rel="stylesheet" href="../styles.css" />
  </head>

  <body>
    <main>
      <h1>Tests — Web Components</h1>

      <template>
        <div class="dialog" aria-labelledby="my-dialog-title" aria-hidden="true">
          <div class="dialog-overlay" data-a11y-dialog-hide></div>
          <div class="dialog-content" role="document">
            <button data-a11y-dialog-hide class="dialog-close" aria-label="Close this dialog window">&times;</button>
            <h1 id="my-dialog-title"></h1>
            <slot></slot>
            <fancy-button data-a11y-dialog-hide>
              Close the dialog
            </fancy-button>
          </div>
        </div>
        <link rel="stylesheet" href="./styles.css" />
      </template>

      <div id="app">
        <fancy-button data-a11y-dialog-show="foobar">
          Open the dialog
        </fancy-button>

        <my-dialog id="foobar" title="Dialog title">
          My dialog content
          <button type="button">Top-level button</button>
          <div>
            <button type="button">Nested button</button>
          </div>
        </my-dialog>
      </div>
    </main>

    <script src="./a11y-dialog.js"></script>
    <script src="./shadow-dom-fixture.js"></script>
    <script>
      class MyDialog extends HTMLElement {
        connectedCallback() {
          // We default to the existing shadow root if there is one because
          // Cypress throws errors when attempting to interact with the journal.
          const shadow = this.shadowRoot ?? this.attachShadow({ mode: "open" })
          const template = document.querySelector("template")
          shadow.appendChild(template.content.cloneNode(true))

          // Pass the id attribute through, and assign the title
          shadow.querySelector(".dialog").id = this.getAttribute("id")
          shadow.querySelector(".dialog h1").innerText = this.getAttribute("title")

          const container = shadow.querySelector(".dialog")
          const dialog = new A11yDialog(container)
          window.instance = dialog
        }
      }

      customElements.define("my-dialog", MyDialog)
    </script>
  </body>
</html>
